﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using Portal.Interface;
using MyLib;
using Portal.Entity;
using System.Collections;
using Portal.Logic;
namespace ProcessControl
{
    public partial class UserInfo : System.Web.UI.UserControl
    {
        IOrg _org = ServiceContainer.Instance().GetService<IOrg>();
        /// <summary>
        /// 表单标题
        /// </summary>
        public string ProcessTitle
        {
            get
            {
                return lblProcessName.Text;
            }
            set
            {
                lblProcessName.Text = value;
            }
        }

        /// <summary>
        /// 流程名称
        /// </summary>
        public string ProcessName
        {
            get
            {
                return fld_PROCESSNAME.Text;
            }
            set
            {
                fld_PROCESSNAME.Text = value;
            }
        }

        public string Type
        {
            get
            {
                return txtType.Text;
            }
            set
            {
                txtType.Text = value;
            }
        }

        /// <summary>
        /// 所对应的表名
        /// </summary>
        public string TableName
        {
            get
            {
                if (string.IsNullOrEmpty(txtTableName.Text))
                {
                    txtTableName.Text = "PROC_" + ProcessName;
                }
                return txtTableName.Text;
            }
            set
            {
                txtTableName.Text = value;
            }
        }
        /// <summary>
        /// 所对应的字表表名
        /// </summary>
        public string TableNameDetail
        {
            get
            {
                //if (string.IsNullOrEmpty(txtTableNameDetail.Text))
                //{
                //    txtTableNameDetail.Text = "PROC_" + ProcessName+"_DT";
                //}
                return txtTableNameDetail.Text;
            }
            set
            {
                txtTableNameDetail.Text = value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public bool ReadOnly
        {
            get
            {
                if (txtReadOnly.Text == "1")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            set
            {
                if (value)
                {
                    txtReadOnly.Text = "1";
                }
                else
                {
                    txtReadOnly.Text = "0";
                }
                fld_COMPANY.Visible = !value;
                fld_PROCESSSUMMARY.Visible = !value;
                lblCOMPANY.Visible = value;
                lblSummary.Visible = value;
            }
        }

        /// <summary>
        /// 实例号
        /// </summary>
        public string Incident
        {
            get
            {
                return fld_INCIDENT.Text;
            }
            set
            {
                fld_INCIDENT.Text = value;
            }
        }

        /// <summary>
        /// 表单Guid，唯一键
        /// </summary>
        public string FormId
        {
            get
            {
                return fld_FORMID.Text;
            }
            set
            {
                fld_FORMID.Text = value;
            }
        }

        /// <summary>
        /// 流程前缀，一般用于流程编号
        /// </summary>
        public string ProcessPrefix
        {
            get
            {
                return txtProcessPrefix.Text;
            }
            set
            {
                txtProcessPrefix.Text = value;
            }
        }

        /// <summary>
        /// 流程摘要
        /// </summary>
        public string Summary
        {
            get
            {
                return fld_PROCESSSUMMARY.Text;
            }
            set
            {
                fld_PROCESSSUMMARY.Text = value;
            }
        }

        /// <summary>
        /// 任务号
        /// </summary>
        public string TaskId
        {
            get
            {
                return txtTaskId.Text;
            }
            set
            {
                txtTaskId.Text = value;
            }
        }

        /// <summary>
        /// 步骤名
        /// </summary>
        public string StepName
        {
            get
            {
                return txtStepName.Text;
            }
            set
            {
                txtStepName.Text = value;
            }
        }


        public string Applicant
        {
            get { return fld_APPLICANT.Text; }
        }

        /// <summary>
        /// 表单数据
        /// </summary>
        public DataSet FormData
        {
            get
            {
                if (ViewState["FormData"] != null)
                {
                    return ViewState["FormData"] as DataSet;
                }
                return new DataSet();
            }
            set
            {
                ViewState["FormData"] = value;
            }
        }
        /// <summary>
        /// 表单明细数据
        /// </summary>
        public DataTable DetailData
        {
            get
            {
                if (ViewState["DetailData"] != null)
                {
                    return ViewState["DetailData"] as DataTable;
                }
                return new DataTable();
            }
            set
            {
                ViewState["DetailData"] = value;
            }
        }
        /// <summary>
        /// 获取上级主管
        /// </summary>
        /// <param name="userAccount"></param>
        /// <returns></returns>
        public string GetDepartmentManager(string userAccount)
        {
            return "";
        }

        /// <summary>
        /// 获取所有与数据库绑定的控件
        /// </summary>
        /// <returns></returns>
        public List<Control> GetAllFieldControl()
        {
            List<Control> controls = new List<Control>();
            foreach (Control ctl in this.Controls)
            {
                if (ctl.ID != null && ctl.ID.StartsWith("fld_"))
                {
                    controls.Add(ctl);
                }
            }
            foreach (Control ctl in this.Parent.Controls)
            {
                if (ctl.ID != null && ctl.ID.StartsWith("fld_"))
                {
                    controls.Add(ctl);
                }
            }
            return controls;
        }

        /// <summary>
        /// 获取所有包含电子表格变量的控件
        /// </summary>
        /// <returns></returns>
        public List<Control> GetAllVarControl()
        {
            List<Control> controls = new List<Control>();
            foreach (Control ctl in this.Controls)
            {
                if (ctl.ID != null && ctl.ID.StartsWith("var_"))
                {
                    controls.Add(ctl);
                }
            }
            foreach (Control ctl in this.Parent.Controls)
            {
                if (ctl.ID != null && ctl.ID.StartsWith("var_"))
                {
                    controls.Add(ctl);
                }
            }
            return controls;
        }

        /// <summary>
        /// 获取所有的电子表格变量
        /// </summary>
        /// <returns></returns>
        public Hashtable GetFormVars(ref Hashtable vars)
        {
            List<Control> controls = GetAllVarControl();
            foreach (Control ctl in controls)
            {
                string key = ctl.ID.Replace("var_", "");
                string value = "";
                if (ctl is Label)
                {
                    value = (ctl as Label).Text;
                }
                if (ctl is TextBox)
                {
                    value = (ctl as TextBox).Text;
                }
                if (ctl is DropDownList)
                {
                    value = (ctl as DropDownList).SelectedValue;
                }
                if (ctl is CheckBox)
                {
                    value = (ctl as CheckBox).Checked == true ? "1" : "0";
                }
                if (ctl is RadioButton)
                {
                    value = (ctl as RadioButton).Checked == true ? "1" : "0";
                }
                if (ctl is HtmlInputRadioButton)
                {
                    value = (ctl as HtmlInputRadioButton).Checked == true ? "1" : "0";
                }
                ////----------添加数组变量赋值    modify by sky 2013-6-7 18:25
                //object objval = null;
                //if (value.Contains("<+>"))
                //{
                //    string[] strVals = value.Replace("<", "").Replace(">", "").Split(new char[] { '+' });
                //    if (strVals.Length > 5)
                //        objval = strVals;
                //    else
                //    {
                //        string[] strNew = new string[] { " ", " ", " ", " ", " " };
                //        strVals.CopyTo(strNew, 0);
                //        objval = strNew;
                //    }
                //}
                //else
                //{
                //    objval = value;
                //}
                //---------------------------------------------------------
                vars.Add(key, value);
            }

            return vars;
        }

        /// <summary>
        /// 从表单中抓取数据，完成后存放在ViewState中
        /// </summary>
        /// <returns></returns>
        public DataSet GetFormData()
        {
            List<Control> controls = GetAllFieldControl();

            DataSet ds = new DataSet();

            DataTable dt = new DataTable("MainTable");

            DataRow dr = dt.NewRow();
            foreach (Control ctl in controls)
            {
                if (ctl.ID.StartsWith("fld_detail_"))//明细表
                {
                    string tableName = ctl.ID.Replace("fld_detail_", "");
                    DataTable dt_detail = GetDetailData(ctl);
                    dt_detail.TableName = tableName;
                    ds.Tables.Add(dt_detail);
                    //if (ctl is GridView)
                    //{
                    //    DataTable dtDetail = ((DataTable)(ctl as GridView).DataSource).Copy();
                    //    dtDetail.TableName = tableName;
                    //    ds.Tables.Add(dtDetail);
                    //}
                    //if (ctl is Repeater)
                    //{
                    //    DataTable dtDetail = ((DataTable)(ctl as Repeater).DataSource).Copy();
                    //    dtDetail.TableName = tableName;
                    //    ds.Tables.Add(dtDetail);
                    //}
                }
                else //主表
                {
                    string columnName = ctl.ID.Replace("fld_", "");
                    dt.Columns.Add(columnName);
                    if (ctl is Label)
                    {
                        dr[columnName] = (ctl as Label).Text;
                    }
                    if (ctl is TextBox)
                    {
                        dr[columnName] = (ctl as TextBox).Text;
                    }
                    if (ctl is DropDownList)
                    {
                        dr[columnName] = (ctl as DropDownList).SelectedValue;
                    }
                    if (ctl is CheckBox)
                    {
                        dr[columnName] = (ctl as CheckBox).Checked == true ? 1 : 0;
                    }
                    if (ctl is RadioButton)
                    {
                        dr[columnName] = (ctl as RadioButton).Checked == true ? 1 : 0;
                    }
                    if (ctl is HtmlInputRadioButton)
                    {
                        dr[columnName] = (ctl as HtmlInputRadioButton).Checked == true ? 1 : 0;
                    }
                }
            }
            dt.Rows.Add(dr);
            ds.Tables.Add(dt);


            FormData = ds;
            return ds;
        }

        /// <summary>
        /// 从数据库中加载数据
        /// </summary>
        public void SetFormData()
        {
            List<Control> controls = GetAllFieldControl();
            //1.加载主表
            string tableName = TableName.Trim();
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(string.Format("select * from {0} where PROCESSNAME='{1}' AND INCIDENT='{2}'", tableName, fld_PROCESSNAME.Text, fld_INCIDENT.Text));

            string FORMID = "";
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                FORMID = dr["FORMID"].ToString();
                foreach (DataColumn col in dt.Columns)
                {
                    Control ctl = controls.Find(p => p.ID == "fld_" + col.ColumnName);
                    if (ctl != null)
                    {
                        string columnName = ctl.ID.Replace("fld_", "");
                        if (ctl is Label)
                        {
                            if (columnName.ToUpper().IndexOf("DATE") >= 0)
                            {
                                (ctl as Label).Text = ConvertUtil.ToDateTime(dr[columnName]).ToShortDateString().Replace("-", "/");
                            }
                            else
                            {
                                (ctl as Label).Text = dr[columnName].ToString();
                            }
                        }
                        if (ctl is TextBox)
                        {
                            (ctl as TextBox).Text = dr[columnName].ToString();
                        }
                        if (ctl is DropDownList)
                        {
                            (ctl as DropDownList).SelectedValue = dr[columnName].ToString();
                        }
                        if (ctl is CheckBox)
                        {
                            if (Convert.ToInt32(dr[columnName]) == 1)
                            {
                                (ctl as CheckBox).Checked = true;
                            }
                            else
                            {
                                (ctl as CheckBox).Checked = false;
                            }
                        }
                        if (ctl is RadioButton)
                        {
                            if (Convert.ToInt32(dr[columnName]) == 1)
                            {
                                (ctl as RadioButton).Checked = true;
                            }
                            else
                            {
                                (ctl as RadioButton).Checked = false;
                            }
                        }
                        if (ctl is HtmlInputRadioButton)
                        {
                            if (Convert.ToInt32(dr[columnName]) == 1)
                            {
                                (ctl as HtmlInputRadioButton).Checked = true;
                            }
                            else
                            {
                                (ctl as HtmlInputRadioButton).Checked = false;
                            }
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(TableNameDetail.Trim()))
            {
                DataTable dt_detail = null;
                if (TableNameDetail.Trim() == "PROC_PERSONREIMBURSEMENT_DT")
                {
                    dt_detail = DataAccess.Instance("BizDB").ExecuteDataTable(string.Format("select * from {0} where  FORMID='{1}' order by IDNO", TableNameDetail, FORMID));
                }
                else
                {
                    dt_detail = DataAccess.Instance("BizDB").ExecuteDataTable(string.Format("select * from {0} where  FORMID='{1}' order by 1,2,3,4 ", TableNameDetail, FORMID));
                    //DataView dgViwe = dt_detail.DefaultView;
                }
                Control ctl = controls.Find(p => p.ID == "fld_detail_" + TableNameDetail);
                if (ctl != null)
                {
                    if (ctl is GridView)
                    {
                        (ctl as GridView).DataSource = dt_detail;
                        (ctl as GridView).DataBind();
                    }
                    if (ctl is Repeater)
                    {
                        (ctl as Repeater).DataSource = dt_detail;
                        (ctl as Repeater).DataBind();
                    }
                    DetailData = dt_detail;
                }
            }

            if (dt != null)
            {
                FormData = dt.DataSet;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                fld_PROCESSNAME.Text = Request.QueryString["ProcessName"];
                fld_INCIDENT.Text = Request.QueryString["Incident"];
                incident.Text = Request.QueryString["Incident"];
                txtTaskId.Text = Request.QueryString["TaskId"];
                txtStepName.Text = Request.QueryString["StepName"];
                txtType.Text = Request.QueryString["Type"];
                txtApplicantAccount.Text = Request.QueryString["UserName"];
                if (string.IsNullOrEmpty(fld_PROCESSNAME.Text))
                {
                    return;
                }
                //新建流程
                if (string.IsNullOrEmpty(fld_INCIDENT.Text) || fld_INCIDENT.Text.Trim() == "0")
                {
                    UserEntity user = _org.GetUserEntity(Page.User.Identity.Name);
                    fld_APPLICANT.Text = user.CNName;
                    var_ApplicantAccount.Text = user.LoginName.Replace("\\", "/"); 
                    fld_REQUESTDATE.Text = DateTime.Now.ToShortDateString().Replace("-", "/");
                    fld_DEPARTMENT.Text = user.Ext01.Substring(0, user.Ext01.IndexOf('['));
                    var_DepartmentId.Text = user.Ext02;
                    var_CenterDepartment.Text = user.Ext03; 
                    var_UserRole.Text = user.JobFunction;
                    var_FuZhuRen.Text = user.Ext07;
                    if (user.Ext03.IndexOf("中心") >= 0 && user.Ext03.IndexOf("运营管理中心") < 0)
                    {   
                        var_DepartmentType.Text = "1";
                    }
                    else if (user.Ext03.IndexOf("国际服务部") >= 0)
                    {
                        var_DepartmentType.Text = "1";
                    }
                    else
                    {
                        var_DepartmentType.Text = "0";
                    }
                    var_DepartmentManager.Text = user.Ext06;
                    var_CenterManager.Text = user.Ext05;
                    //员工类型
                    if (var_ApplicantAccount.Text.Trim().ToUpper() == var_DepartmentManager.Text.Trim().ToUpper())
                    {
                        var_ApplicantType.Text = "1";
                    }
                    if (var_ApplicantAccount.Text.Trim().ToUpper() == var_CenterManager.Text.Trim().ToUpper() && var_ApplicantAccount.Text.Trim() != "")
                    {
                        var_ApplicantType.Text = "2";
                    }
                    if (user.JobFunction.IndexOf("总经理") >= 0 && user.JobFunction.IndexOf("副总经理") < 0)
                    {
                        var_ApplicantType.Text = "3";
                    }
                    if (user.JobFunction.IndexOf("中心副主任") >= 0)
                    {
                        var_ApplicantType.Text = "4";
                    }
                    fld_FORMID.Text = Guid.NewGuid().ToString();
                    SerialNoLogic sn = new SerialNoLogic();
                    string documentNo = string.Format("{0}{1}{2}{3}{4}", ProcessPrefix, DateTime.Now.Year, DateTime.Now.Month.ToString().PadLeft(2, '0'), DateTime.Now.Day.ToString().PadLeft(2, '0'), sn.GetSerialNo(ProcessPrefix, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).ToString().PadLeft(4, '0'));
                    fld_DOCUMENTNO.Text = documentNo;
                    lblDocumentNo.Visible = false;

                }
                else //打开待办或已办
                {
                    //重新发起加载var变量 modify by jlchen 9.25
                    if (txtStepName.Text.Trim() == "重新发起")
                    {
                        UserEntity user = _org.GetUserEntity(Page.User.Identity.Name);
                        //fld_APPLICANT.Text = user.CNName;
                        var_ApplicantAccount.Text = user.LoginName.Replace("\\", "/");
                        //fld_REQUESTDATE.Text = DateTime.Now.ToShortDateString().Replace("-", "/");
                        //fld_DEPARTMENT.Text = user.Ext01.Substring(0, user.Ext01.IndexOf('['));
                        var_DepartmentId.Text = user.Ext02;
                        var_CenterDepartment.Text = user.Ext03;
                        var_UserRole.Text = user.JobFunction;
                        var_FuZhuRen.Text = user.Ext07;
                        if (user.Ext03.IndexOf("中心") >= 0 && user.Ext03.IndexOf("运营管理中心") < 0)
                        {
                            var_DepartmentType.Text = "1";
                        }
                        else if (user.Ext03.IndexOf("国际服务部") >= 0)
                        {
                            var_DepartmentType.Text = "1";
                        }
                        else
                        {
                            var_DepartmentType.Text = "0";
                        }
                        var_DepartmentManager.Text = user.Ext06;
                        var_CenterManager.Text = user.Ext05;
                        //员工类型
                        if (var_ApplicantAccount.Text.Trim().ToUpper() == var_DepartmentManager.Text.Trim().ToUpper())
                        {
                            var_ApplicantType.Text = "1";
                        }
                        if (var_ApplicantAccount.Text.Trim().ToUpper() == var_CenterManager.Text.Trim().ToUpper() && var_ApplicantAccount.Text.Trim() != "")
                        {
                            var_ApplicantType.Text = "2";
                        }
                        if (user.JobFunction.IndexOf("总经理") >= 0 && user.JobFunction.IndexOf("副总经理") < 0)
                        {
                            var_ApplicantType.Text = "3";
                        }
                        if (user.JobFunction.IndexOf("中心副主任") >= 0)
                        {
                            var_ApplicantType.Text = "4";
                        }
                        //fld_FORMID.Text = Guid.NewGuid().ToString();
                        //SerialNoLogic sn = new SerialNoLogic();
                        //string documentNo = string.Format("{0}{1}{2}{3}{4}", ProcessPrefix, DateTime.Now.Year, DateTime.Now.Month.ToString().PadLeft(2, '0'), DateTime.Now.Day.ToString().PadLeft(2, '0'), sn.GetSerialNo(ProcessPrefix, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).ToString().PadLeft(4, '0'));
                        //fld_DOCUMENTNO.Text = documentNo;
                        //lblDocumentNo.Visible = false;
                    }
                    lblDocumentNo.Visible = false;
                    //加载表单数据
                    SetFormData();

                    lblSummary.Text = fld_PROCESSSUMMARY.Text;
                    lblCOMPANY.Text = fld_COMPANY.SelectedValue;
                }

                //从草稿打开
                if (txtType.Text.ToUpper().Trim() == "DRAFT")
                {
                    UserEntity user = _org.GetUserEntity(Page.User.Identity.Name);
                    var_ApplicantAccount.Text = user.LoginName.Replace("\\", "/");
                    var_DepartmentId.Text = user.Ext02;
                    var_CenterDepartment.Text = user.Ext03;
                    var_FuZhuRen.Text = user.Ext07;
                    var_UserRole.Text = user.JobFunction;
                    if (user.Ext03.IndexOf("中心") >= 0 && user.Ext03.IndexOf("运营管理中心") < 0)
                    {
                        var_DepartmentType.Text = "1";
                    }
                    else if (user.Ext03.IndexOf("国际服务部") >= 0)
                    {
                        var_DepartmentType.Text = "1";
                    }
                    else
                    {
                        var_DepartmentType.Text = "0";
                    }
                    var_DepartmentManager.Text = user.Ext06;
                    var_CenterManager.Text = user.Ext05;
                    //员工类型
                    if (var_ApplicantAccount.Text.Trim().ToUpper() == var_DepartmentManager.Text.Trim().ToUpper())
                    {
                        var_ApplicantType.Text = "1";
                    }
                    if (var_ApplicantAccount.Text.Trim().ToUpper() == var_CenterManager.Text.Trim().ToUpper())
                    {
                        var_ApplicantType.Text = "2";
                    }
                    if (user.JobFunction.IndexOf("总经理") >= 0 && user.JobFunction.IndexOf("副总经理") < 0)
                    {
                        var_ApplicantType.Text = "3";
                    }
                    if (user.JobFunction.IndexOf("中心副主任") >= 0)
                    {
                        var_ApplicantType.Text = "4";
                    }
                }
            }
        }

        /// <summary>
        /// 明细行新增一行
        /// </summary>
        /// <param name="ctl"></param>
        public void AddNewRow(Control ctl)
        {
            if (DetailData.Columns.Count == 0)
            {
                SetFormData();
            }
            DataTable dt = DetailData.Clone();
            dt = GetDetailData(ctl);
            dt.Rows.Add(dt.NewRow());
            if (ctl is GridView)
            {
                GridView gv = ctl as GridView;
                gv.DataSource = dt;
                gv.DataBind();
            }
            if (ctl is Repeater)
            {
                Repeater rp = ctl as Repeater;
                rp.DataSource = dt;
                rp.DataBind();
            }
        }

        /// <summary>
        /// 明细行删除一行
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="e"></param>
        public void DeleteRow(Control ctl, RepeaterCommandEventArgs e)
        {
            DataTable dt = DetailData.Clone();
            if (e.CommandName == "del")
            {
                dt = GetDetailData(ctl);
                dt.Rows[e.Item.ItemIndex].Delete();
                dt.AcceptChanges();
            }
            if (ctl is GridView)
            {
                GridView gv = ctl as GridView;
                gv.DataSource = dt;
                gv.DataBind();
            }
            if (ctl is Repeater)
            {
                Repeater rp = ctl as Repeater;
                rp.DataSource = dt;
                rp.DataBind();
            }
        }

        /// <summary>
        /// 获取明细行中的数据
        /// </summary>
        /// <param name="ctl">数据绑定控件</param>
        /// <returns></returns>
        public DataTable GetDetailData(Control ctl)
        {
            DataTable dt = DetailData.Clone();
            if (ctl is GridView)
            {
                GridView gv = ctl as GridView;
                foreach (GridViewRow item in gv.Rows)
                {
                    GetControl(item.Controls, ref dt);
                }
            }
            if (ctl is Repeater)
            {
                Repeater rp = ctl as Repeater;
                foreach (RepeaterItem item in rp.Items)
                {
                    GetControl(item.Controls, ref dt);
                }
            }
            return dt;
        }

        /// <summary>
        /// 获取明细行控件的值，存放到DataTable中
        /// </summary>
        /// <param name="item"></param>
        /// <param name="dt"></param>
        public void GetControl(ControlCollection item, ref DataTable dt)
        {
            DataRow dr = dt.NewRow();
            foreach (Control ctl in item)
            {
                if (ctl.ID != null && ctl.ID.StartsWith("fld_"))
                {
                    string columnName = ctl.ID.Replace("fld_", "");
                    if (columnName == "FORMID")
                    {
                        dr[columnName] = fld_FORMID.Text;
                        continue;
                    }
                    if (ctl is Label)
                    {
                        dr[columnName] = (ctl as Label).Text;
                    }
                    if (ctl is TextBox)
                    {
                        if ((ctl as TextBox).Text.Trim() != "")
                        {
                            dr[columnName] = (ctl as TextBox).Text;
                        }
                    }
                    if (ctl is DropDownList)
                    {
                        dr[columnName] = (ctl as DropDownList).SelectedValue;
                    }
                    if (ctl is CheckBox)
                    {
                        dr[columnName] = (ctl as CheckBox).Checked == true ? 1 : 0;
                    }
                    if (ctl is RadioButton)
                    {
                        dr[columnName] = (ctl as RadioButton).Checked == true ? 1 : 0;
                    }
                }
            }
            dt.Rows.Add(dr);
        }

    }
}